// 验证当前页面是否为xhs网站
if (window.location.hostname.includes('xiaohongshu.com')) {
  console.log('xhsCookie获取工具已启动');
  
  // 创建悬浮窗
  function createSidebar() {
    const sidebar = document.createElement('div');
    sidebar.id = 'xhs-cookie-sidebar';
    sidebar.innerHTML = `
      <div class="xhs-cookie-container">
        <div class="close-button" title="关闭">×</div>
        <div class="header draggable">
          <h2 style="font-size: 12px;">sodao-xhs-Cookie获取工具</h2>
          <div style="font-size: 12px; margin-top: 4px;">
            <a href="https://xhs.sohook.com/" target="_blank" style="color: #666; text-decoration: none;">@搜获客</a>
          </div>
        </div>
        <textarea id="xhs-cookie-data" readonly placeholder="等待获取cookie..."></textarea>
        <button id="xhs-copy-button">复制Cookie</button>
        <div id="xhs-status"></div>
      </div>
    `;
    document.body.appendChild(sidebar);
    
    // 设置可拖拽功能
    makeDraggable(sidebar);
    
    // 关闭按钮功能
    sidebar.querySelector('.close-button').addEventListener('click', () => {
      sidebar.style.display = 'none';
    });
    
    // 获取cookie
    function getCookies() {
      const cookieData = document.getElementById('xhs-cookie-data');
      const status = document.getElementById('xhs-status');
      
      updateStatus('正在获取Cookie...');
      
      chrome.runtime.sendMessage({action: 'getCookies'}, response => {
        if (chrome.runtime.lastError) {
          cookieData.value = "获取cookie失败：" + chrome.runtime.lastError.message;
          updateStatus("获取失败", false);
          return;
        }
        
        if (response && response.cookies) {
          cookieData.value = response.cookies;
          updateStatus("已获取到Cookie", true);
        } else {
          cookieData.value = "未找到xhs相关cookie，请先登录xhs网站";
          updateStatus('未找到Cookie，请先登录', false);
        }
      });
    }
    
    // 复制功能
    document.getElementById('xhs-copy-button').addEventListener('click', async () => {
      updateStatus('正在更新Cookie...');
      
      // 先获取最新cookie
      chrome.runtime.sendMessage({action: 'getCookies'}, async response => {
        if (chrome.runtime.lastError) {
          updateStatus("获取cookie失败：" + chrome.runtime.lastError.message, false);
          return;
        }
        
        const cookieData = document.getElementById('xhs-cookie-data');
        
        if (response && response.cookies) {
          cookieData.value = response.cookies;
          
          try {
            await navigator.clipboard.writeText(response.cookies);
            updateStatus("Cookie已复制到剪贴板！", true);
          } catch (error) {
            updateStatus("复制失败：" + error.message, false);
          }
        } else {
          cookieData.value = "未找到xhs相关cookie，请先登录xhs网站";
          updateStatus('未找到Cookie，请先登录', false);
        }
      });
    });
    
    // 更新状态文本
    function updateStatus(message, isSuccess = true) {
      const status = document.getElementById('xhs-status');
      status.textContent = message;
      status.className = isSuccess ? 'success' : 'error';
    }

    // 初始化获取cookie
    getCookies();
  }

  // 使元素可拖拽
  function makeDraggable(element) {
    const container = element.querySelector('.xhs-cookie-container');
    const header = element.querySelector('.draggable');
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    
    header.addEventListener('mousedown', dragStart);
    
    function dragStart(e) {
      if (header.contains(e.target)) {
        isDragging = true;
        initialX = e.clientX - element.offsetLeft;
        initialY = e.clientY - element.offsetTop;
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', dragEnd);
      }
    }
    
    function drag(e) {
      if (isDragging) {
        e.preventDefault();
        
        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;
        
        // 限制在视窗内
        const maxX = window.innerWidth - element.offsetWidth;
        const maxY = window.innerHeight - element.offsetHeight;
        
        currentX = Math.min(Math.max(0, currentX), maxX);
        currentY = Math.min(Math.max(0, currentY), maxY);
        
        element.style.left = currentX + 'px';
        element.style.top = currentY + 'px';
        element.style.right = 'auto';
      }
    }
    
    function dragEnd() {
      isDragging = false;
      document.removeEventListener('mousemove', drag);
      document.removeEventListener('mouseup', dragEnd);
    }
  }
  
  // 等待页面加载完成后创建悬浮窗
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createSidebar);
  } else {
    createSidebar();
  }
}
